<template>
  <el-scrollbar :height="scrollHeight?scrollHeight:isTagsview ? `calc(100vh - 154px)` : `calc(100vh - 120px)`">
    <div>
      <zh-form ref="formRef" style="width: 96%" :md="12" :lg="12" :xl="12" :model="dataCenterInfo" :rules="rules"
               label-width="200px">
        <!--        <zh-form-input prop="id" label="id" placeholder="" v-model="dataCenterInfo.id"
                               disabled></zh-form-input>-->
        <zh-form-input prop="tableId" label="表Id" placeholder=""
                       v-model="dataCenterInfo.tableId"></zh-form-input>
        <zh-form-input prop="columnName" label="字段名" placeholder=""
                       v-model="dataCenterInfo.columnName"></zh-form-input>
        <zh-form-input prop="columnComment" label="字段中文名" placeholder=""
                       v-model="dataCenterInfo.columnComment"></zh-form-input>
        <zh-form-input prop="columnDesc" label="字段备注" placeholder=""
                       v-model="dataCenterInfo.columnDesc"></zh-form-input>
        <!--        <zh-form-select
                    prop="dataType"
                    label="字段类型"
                    :options="state.dictData.tabledatatype"
                    placeholder="请选择"
                    v-model="dataCenterInfo.dataType"
                ></zh-form-select>-->
        <zh-form-select
            prop="dataType"
            label="字段类型"
            :options="state.dictData.fieldType"
            placeholder="请选择"
            v-model="dataCenterInfo.dataType"
        ></zh-form-select>
        <!--        <zh-form-select
                    prop="dataType"
                    label="字段类型"
                    filterable :lazy="true"
                    @change="(val) => {}"
                    :funcCode="'fieldTypeMeta0001'"
                    :fieldNames="{label: 'filedTypeName', value: 'filedTypeName', option: 'children'}"
                    placeholder="请选择"
                    v-model="dataCenterInfo.dataType"
                ></zh-form-select>-->
        <zh-form-input prop="dataLength" label="字段长度" placeholder="" :disabled="dataDisabled('length')" type="number"
                       v-model.number="dataCenterInfo.dataLength"></zh-form-input>
        <zh-form-input prop="dataLength" label="精度" placeholder="" :disabled="dataDisabled('precision')" type="number"
                       v-model.number="dataCenterInfo.dataLength"></zh-form-input>
        <zh-form-input prop="dataScale" label="小数位数" :disabled="dataDisabled('scale')" placeholder="" type="number"
                       v-model.number="dataCenterInfo.dataScale"></zh-form-input>
        <zh-form-select
            prop="primaryKey"
            label="主键标志"
            :options="state.dictData.primaryKey"
            placeholder="请选择"
            v-model="dataCenterInfo.primaryKey"
        ></zh-form-select>
        <zh-form-select
            prop="nullable"
            label="是否为空"
            :options="state.dictData.nullable"
            placeholder="请选择"
            v-model="dataCenterInfo.nullable"
        ></zh-form-select>
        <zh-form-select
            prop="safelevel"
            label="字段分级"
            :options="state.dictData.safelevel"
            placeholder="请选择"
            v-model="dataCenterInfo.safeLevel"
        ></zh-form-select>
        <zh-form-select
            prop="desensitization"
            label="脱敏类型"
            :options="state.dictData.desensitization"
            placeholder=""
            v-model="dataCenterInfo.desensitization"
        ></zh-form-select>
        <zh-form-select
            prop="encryption"
            label="是否加密"
            :options="state.dictData.encryption"
            placeholder="请选择"
            v-model="dataCenterInfo.encryption"
        ></zh-form-select>
      </zh-form>
    </div>
    <div>
      <zh-form ref="propertyFormRef" style="width: 96%" :md="12" :lg="12" :xl="12" :model="state.propertyMetaFormData"
               :rules="state.propertyMetaFormRules" label-width="200px">
        <!--        <zh-form-input prop="fieldId" label="表Id" placeholder="" v-model="dataCenterInfo.tableId"></zh-form-input>-->
        <zh-form-select prop="propertyType" label="属性类型" v-model="state.propertyMetaFormData.propertyType"
                        :options="state.dictData.propertyType" placeholder="请选择"></zh-form-select>
        <zh-form-input prop="dictField" label="字典字段" :disabled="state.propertyMetaFormData.propertyType != '2'"
                       v-model="state.propertyMetaFormData.dictField"></zh-form-input>
        <zh-form-input prop="dateFormat" label="日期格式" :disabled="state.propertyMetaFormData.propertyType != '3'"
                       v-model="state.propertyMetaFormData.dateFormat"></zh-form-input>
        <zh-form-select prop="propertyVisible" label="是否可见" v-model="state.propertyMetaFormData.propertyVisible"
                        :options="state.dictData.isVisible" placeholder="请选择"></zh-form-select>
        <zh-form-select prop="isParam" label="是否作为输入参数" v-model="state.propertyMetaFormData.isParam"
                        :options="state.dictData.isParam" placeholder="请选择"></zh-form-select>
        <zh-form-select prop="outParam" label="是否作为输出参数" v-model="state.propertyMetaFormData.outParam"
                        :options="state.dictData.outParam" placeholder="请选择"></zh-form-select>
        <zh-form-input prop="width" label="表格字段宽度" v-model="state.propertyMetaFormData.width"></zh-form-input>
      </zh-form>
    </div>
  </el-scrollbar>
</template>

<script lang="ts" setup name="DataCenterForm">
//------------------接收传入参数------------------------
import {computed} from "vue";

const props = defineProps({
  scrollHeight: {
    type: String,
    default: ''
  },
  cotablemetaInfo: Object
});

//------------------定义子组件---------------------------
const formRef = ref();
const propertyFormRef = ref();

//------------------内部变量定义-------------------------
const state = reactive({
  hideChecked: false,
  confirmLoading: false,
  dictData: {} as any,
  initData: {},
  appDict: [],
  orgDict: [],
  devOrgDict: [],
  envDict: [],
  propertyMetaFormData: {
    propertyId: '',
    fieldId: '',
    propertyType: '',
    dictField: '',
    dateFormat: '',
    propertyVisible: '',
    isParam: '',
    outParam: '',
    width: '',
  },
  propertyMetaFormRules: {
    propertyType: [{required: true, message: '属性类型必填'}]
  },
  fieldTypeMetas: [],
  datasourceType: ''
});
const rules = reactive({
  tableId: [
    {
      required: true,
      message: '请输入表Id',
      trigger: 'blur',
    },
  ],
  columnName: [
    {
      required: true,
      message: '请输入字段名',
      trigger: 'blur',
    },
  ],
  dataType: [
    {
      required: true,
      message: '请输入字段类型',
      trigger: 'blur',
    },
  ],
  dataLength: [
    {
      required: true,
      message: '请输入字段长度',
      trigger: 'blur',
    }
  ],
  dataScale: [],
  nullable: [
    {
      required: true,
      message: '请输入是否为空',
      trigger: 'blur',
    },
  ],

});
let dataCenterInfo = reactive({tableId: '', id: '', encryption: '', dataLength: {type: Number, default: 0}, dataType: ''})
const selectField = ref({});
const {isTagsview} = storeToRefs($store.theme);

const dataDisabled = computed(() => {
  return (optionField) => {
    let index = state.fieldTypeMetas.findIndex(fieldTypeMeta => {
      return fieldTypeMeta.fieldTypeName == dataCenterInfo.dataType && fieldTypeMeta.optionName == optionField;
    });
    return index == -1;
  }
})

watch(
    () => props.cotablemetaInfo,
    (cotablemetaInfo: any) => {
      if (cotablemetaInfo.id) {
        findDataCenterInfo(cotablemetaInfo);
        findPropertyMetaInfo(cotablemetaInfo);
        findDataSourceInfo(cotablemetaInfo);
      } else {
        Object.assign(dataCenterInfo, cotablemetaInfo);
        Object.assign(state.propertyMetaFormData, {
          propertyId: '',
          fieldId: cotablemetaInfo.id,
          propertyType: '',
          dictField: '',
          dateFormat: '',
          propertyVisible: '',
          isParam: '',
          width: '',
        });
      }
    },
    {
      deep: true,
    }
);
watch(
    () => dataCenterInfo.dataType,
    () => {
      let dataTypeMetas = state.fieldTypeMetas.filter(fieldTypeMeta => {
        return fieldTypeMeta.fieldTypeName == dataCenterInfo.dataType;
      });
      rules.dataLength = [];
      rules.dataScale = [];
      dataTypeMetas.forEach(dataTypeMeta => {
        if (dataTypeMeta.optionName == 'length') {
          rules.dataLength = [{
            required: true,
            message: '请输入字段长度',
            trigger: 'blur',
          },
            {
              type: 'number',
              min: dataTypeMeta.optionMinVal, max: dataTypeMeta.optionMaxVal,
              message: `字段长度必须在${dataTypeMeta.optionMinVal}-${dataTypeMeta.optionMaxVal}`,
              trigger: 'blur',
            }]
        } else if (dataTypeMeta.optionName == 'precision') {
          rules.dataLength = [{
            required: true,
            message: '请输入精度',
            trigger: 'blur',
          },
            {
              type: 'number',
              min: dataTypeMeta.optionMinVal,
              max: dataTypeMeta.optionMaxVal,
              message: `精度必须在${dataTypeMeta.optionMinVal}-${dataTypeMeta.optionMaxVal}`,
              trigger: 'blur',
            }]
        } else if (dataTypeMeta.optionName == 'scale') {
          rules.dataScale = [{
            required: true,
            message: '请输入小数位数',
            trigger: 'blur',
          },
            {
              type: 'number',
              min: dataTypeMeta.optionMinVal,
              max: dataTypeMeta.optionMaxVal,
              message: `小数位数必须在${dataTypeMeta.optionMinVal}-${dataTypeMeta.optionMaxVal}`,
              trigger: 'blur',
            }]
        }
      })
    }
);

//------------------定义调用方法-------------------------
// function setInitDate(info) {
//     formRef.value?.resetFields();
//     if (info) {
//         dataCenterInfo.value = info;
//     }
// }
//保存数据
const saveForm = async () => {
  //校验表单
  let chenckFlag = await formRef.value.checkForm();
  if (chenckFlag) {
    let saveForm = Object.assign({}, dataCenterInfo);
    console.log("saveFormsaveForm", saveForm)
    if (!saveForm.id) {
      let res = await $api.common.send.post('coTableFieldMeta0004', saveForm);
      res.saveType = 'add';
      res.result.nodeType = '1'
      console.log('res coTableFieldMeta0004', res)
      dataCenterInfo.id = res.result.id;
      //校验表单
      chenckFlag = await propertyFormRef.value.checkForm();
      console.log('chenckFlag', chenckFlag)
      if (chenckFlag) {
        let saveForm = Object.assign(state.propertyMetaFormData, {fieldId: dataCenterInfo.id});
        await $api.common.send.post('propertyMeta0004', saveForm);
      }
      return res;
    } else {
      let res = await $api.common.send.post('coTableFieldMeta0005', saveForm);
      res.saveType = 'edit';
      res.result.nodeType = '1';
      //校验表单
      chenckFlag = await propertyFormRef.value.checkForm();
      if (chenckFlag) {
        console.log('state.propertyMetaFormData', state.propertyMetaFormData);
        let saveForm = state.propertyMetaFormData;
        await $api.common.send.post(saveForm.propertyId ? 'propertyMeta0005' : 'propertyMeta0004', saveForm);
      }
      return res;
    }
  }
}

const findDataCenterInfo = (cotablemetaInfo) => {
  const params = {id: cotablemetaInfo.id};
  if (cotablemetaInfo.nodeType == "1") {
    $api.common.send.post('coTableFieldMeta0002', params).then((res) => {
      dataCenterInfo = Object.assign(dataCenterInfo, res.result || {});
      dataCenterInfo.dataLength = Number(dataCenterInfo.dataLength);
      dataCenterInfo.dataScale = Number(dataCenterInfo.dataScale);
      selectField.value = res.result || {};
    })
  }
}

const findPropertyMetaInfo = (cotablemetaInfo) => {
  const params = {fieldId: cotablemetaInfo.id};
  if (cotablemetaInfo.nodeType == "1") {
    $api.common.send.post('propertyMeta0001', params).then((res) => {
      if (res.code == '0' && res.result.list.length > 0) {
        Object.assign(state.propertyMetaFormData, res.result.list[0]);
      } else {
        Object.assign(state.propertyMetaFormData, {
          propertyId: '',
          fieldId: cotablemetaInfo.id,
          propertyType: '',
          dictField: '',
          dateFormat: '',
          propertyVisible: '',
          isParam: '',
          width: '',
        });
      }
    })
  }
}

const findDataSourceInfo = (cotablemetaInfo) => {
  const params = {dataSourceid: cotablemetaInfo.datasourceId};
  if (cotablemetaInfo.datasourceId) {
    $api.common.send.post('dataSource0002', params).then((res) => {
      if (res.code == '0') {
        state.datasourceType = res.result.dataSourcetype;
        findFieldTypeMetas();
      } else {
        state.datasourceType = '';
      }
    });
  }
}

const findFieldTypeMetas = () => {
  $api.common.send.post('fieldTypeMeta0001', {pageSize: 100, datasourceType: state.datasourceType}).then((res) => {
    if (res.code == 0) {
      state.fieldTypeMetas = res.result.list;
      let fieldTypes = Array.from(new Set(state.fieldTypeMetas.map(fieldTypeMeta => fieldTypeMeta.fieldTypeName)));
      fieldTypes = fieldTypes.map(fieldType => {
        return {dictKey: fieldType, dictValue: fieldType, option: 'children'}
      });
      state.dictData.fieldType = fieldTypes;
    }
  })
}

//------------------初始化------------------------------
const params = {
  dictFields: 'tabledatatype,primaryKey,nullable,safelevel,desensitization,propertyType',
};
$api.common.getBatchDict.post(params).then((res) => {
  state.dictData = res.result;
  state.dictData.isVisible = [{dictKey: '0', dictValue: '不可见'}, {dictKey: '1', dictValue: '可见'}];
  state.dictData.isParam = [{dictKey: '0', dictValue: '不为参数'}, {dictKey: '1', dictValue: '作为参数'}];
  state.dictData.outParam = [{dictKey: '0', dictValue: '不为输出参数'}, {dictKey: '1', dictValue: '作为输出参数'}];
  state.dictData.encryption = [{dictKey: '0', dictValue: '不加密'}, {dictKey: '1', dictValue: '加密'}];
});
findFieldTypeMetas();

//------------设置给父组件调用的数据/方法(组件)-----------
defineExpose({saveForm, dataCenterInfo, findDataCenterInfo, selectField});
</script>
